package com.init.bootframe.system.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.init.bootframe.system.dao.IRoleDao;
import com.init.bootframe.system.dao.IUserDao;
import com.init.bootframe.system.service.IRoleService;
import com.init.bootframe.system.vo.RoleModuleVO;
import com.init.bootframe.system.vo.RolePermissionsVO;
import com.init.bootframe.system.vo.RoleVO;
import com.init.bootframe.util.TmompConstant;
import com.init.bootframe.util.TmompUser;
import com.init.bootframe.util.TmompUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色service
 */
@Service
public class RoleServiceImpl implements IRoleService {

    private Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class); //日志

    @Autowired
    private IRoleDao roleDao; //角色dao

    @Autowired
    private IUserDao userDao;//用户dao

    /**
     * 角色列表查询
     * @param roleVO
     * @return
     */
    @Override
    public JSONObject findRoleList(RoleVO roleVO) {
        JSONObject jsonObject = new JSONObject();
        // 角色设置组织code
        roleVO.setOrgCode(TmompUser.getCurrentUserInfo().getOrgCode());
        // 查询集合数据总数
        int total = roleDao.findRoleListCount(roleVO);
        // 查询集合数据
        List<RoleVO> resultLsit = new ArrayList<RoleVO>();
        if (total > 0) {
            resultLsit = roleDao.findRoleList(roleVO);
        }
        jsonObject.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_ROWS, resultLsit);
        jsonObject.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_TOTAL, total);
        return jsonObject;
    }

    /**
     * 添加角色
     * @param roleVO
     * @return
     */
    @Override
    public Map<String, Object> addRole(RoleVO roleVO) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            // 角色设置组织code
            if (null == roleVO.getOrgId() || "".equals(roleVO.getOrgId())) {
                // 默认当前登录组织
                roleVO.setOrgId(TmompUser.getCurrentUserInfo().getOrgId());
            }
            // 设置角色状态
            roleVO.setStatus(TmompConstant.BaseDataConstant.STATUS_EFFECTIVE);
            // 添加角色
            roleDao.addRole(roleVO);
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_RESULT, Boolean.TRUE);
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_MSG, "添加角色成功！");
            logger.debug("添加角色成功！");
        } catch (Exception e) {
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_RESULT, Boolean.FALSE);
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_MSG, "添加角色失败！");
            logger.error("添加角色失败！" + e.getMessage());
            // 手动事物回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return resultMap;
    }

    /**
     * 修改角色
     * @param roleVO
     * @return
     */
    @Override
    public Map<String, Object> updateRole(RoleVO roleVO) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            // 修改角色
            if (roleVO.getRoleId() != null && !"".equals(roleVO.getRoleId())) {
                // 角色设置组织code
                if (null == roleVO.getOrgId() || "".equals(roleVO.getOrgId())) {
                    // 默认当前登录组织
                    roleVO.setOrgId(TmompUser.getCurrentUserInfo().getOrgId());
                }
                roleDao.updateRole(roleVO);
                resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_RESULT, Boolean.TRUE);
                resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_MSG, "修改角色成功！");
                logger.debug("修改角色成功！");
            }
        } catch (Exception e) {
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_RESULT, Boolean.FALSE);
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_MSG, "修改角色失败！");
            logger.error("修改角色失败！" + e.getMessage());
            // 手动事物回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultMap;
    }

    /**
     * 查询角色详情
     * @param roleVO
     * @return
     */
    @Override
    public RoleVO findRole(RoleVO roleVO) {
        RoleVO resultUser = roleDao.findRole(roleVO);
        // 查询用户角色信息
        RolePermissionsVO rpVO = new RolePermissionsVO();
        rpVO.setRoleId(roleVO.getRoleId());
        List<RolePermissionsVO> rpVOList = roleDao.findRolePermissionsList(rpVO);
        resultUser.setRpVOList(rpVOList);
        return resultUser;
    }

    /**
     * 删除角色
     * @param roleVO
     * @return
     */
    @Override
    public Map<String, Object> deleteRole(RoleVO roleVO) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            // 修改角色状态
            roleVO.setStatus(TmompConstant.BaseDataConstant.STATUS_INVALID);
            roleDao.deleteRole(roleVO);
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_MSG, "删除角色成功！");
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_RESULT, Boolean.TRUE);
            logger.debug("删除角色成功！");
        } catch (Exception e) {
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_RESULT, Boolean.FALSE);
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_MSG, "删除角色失败！");
            logger.error("删除角色失败！" + e.getMessage());
            // 手动事物回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultMap;
    }

    /**
     * 角色授权
     * @param roleVO
     * @return
     */
    @Override
    public Map<String, Object> updateRoleAuth(RoleVO roleVO) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String menuJson = roleVO.getMenuNodes();
            // 批量操作菜单权限集合
            List<RolePermissionsVO> menuIdList = new ArrayList<RolePermissionsVO>();
            if (null != menuJson && !"".equals(menuJson)) {
                // JSON数组对象
                JSONArray jsonArray = JSONArray.fromObject(menuJson);
                // 判断是否为空
                if (null != jsonArray && !jsonArray.isEmpty()) {
                    Object[] os = jsonArray.toArray();
                    for (int i = 0; i < os.length; i++) {
                        JSONObject jsonObj = JSONObject.fromObject(os[i]);
                        RolePermissionsVO rpVO = new RolePermissionsVO();
                        String menuId = jsonObj.get("menuId").toString();
                        // 排除根目录
                        if (!"0".equals(menuId)) {
                            rpVO.setMenuId(menuId);// 栏目Id
                            rpVO.setRoleId(roleVO.getRoleId());// 角色Id
                            menuIdList.add(rpVO);
                        }
                    }
                }
                // 删除角色权限
                RolePermissionsVO delRolePermVO = new RolePermissionsVO();
                delRolePermVO.setRoleId(roleVO.getRoleId());
                roleDao.deleteRolePermissions(delRolePermVO);
                // 添加角色权限
                if (menuIdList.size() > 0) {
                    for (int j = 0; j < menuIdList.size(); j++) {
                        roleDao.addRolePermissions(menuIdList.get(j));
                    }
                }
            }
            // 批量操作功能权限
            if (null != roleVO.getModuleIds() && !"".equals(roleVO.getModuleIds())) {
                // 删除角色功能权限
                RoleModuleVO roleModulePramVO = new RoleModuleVO();
                roleModulePramVO.setRoleId(roleVO.getRoleId());
                roleDao.deleteRoleModule(roleModulePramVO);
                String[] moduleIds = roleVO.getModuleIds().split(",");
                // 添加角色功能权限
                for (int j = 0; j < moduleIds.length; j++) {
                    RoleModuleVO roleModuleVO = new RoleModuleVO();
                    roleModuleVO.setRoleId(roleVO.getRoleId());
                    roleModuleVO.setModuleId(moduleIds[j]);
                    roleDao.addRoleModule(roleModuleVO);
                }
            }else{
                // 删除角色功能权限
                RoleModuleVO roleModulePramVO = new RoleModuleVO();
                roleModulePramVO.setRoleId(roleVO.getRoleId());
                roleDao.deleteRoleModule(roleModulePramVO);
            }
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_RESULT, Boolean.TRUE);
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_MSG, "角色授权成功！");
            logger.debug("角色授权成功！");
        } catch (Exception e) {
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_RESULT, Boolean.FALSE);
            resultMap.put(TmompConstant.BaseDataConstant.DEFAULT_VALUE_MSG, "角色授权失败！");
            logger.error("角色授权失败！" + e.getMessage());
            // 手动事物回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultMap;
    }

    /**
     * 查询有效角色集合
     */
    public List<RoleVO> findRoles(RoleVO roleVO) {
        // 设置有效时间
        roleVO.setStartValidDate(TmompUtils.getCurrentDate(TmompConstant.BaseDataConstant.FORMATE_DATA2));
        // 设置角色状态
        roleVO.setStatus(TmompConstant.BaseDataConstant.STATUS_EFFECTIVE);
        // 设置用户组织
        if (StringUtils.isEmpty(roleVO.getOrgId())) {
            roleVO.setOrgId(TmompUser.getCurrentUserInfo().getOrgId());
        }
        List<RoleVO> resultList = roleDao.findRoles(roleVO);
        return resultList;
    }

    /**
     * 查询有效角色功能集合
     * @param roleModuleVO
     * @return
     */
    @Override
    public List<RoleModuleVO> findRoleModuleList(RoleModuleVO roleModuleVO) {
        return roleDao.findRoleModuleList(roleModuleVO);
    }
}
